function sendRequest(settings) {

    function object2Parameter(obj) {
        var r = "";
        for (attr in obj) {
            var p = attr + "=" + obj[attr];
            r += p + "&";
        }
        return r.substring(0, r.length - 1);
    }

    var setting = {
        type: (function() {
            if (settings.type) {
                return settings.type.toString().trim();
            } else {
                return "GET";
            }
        })(),
        contentType: (function() {
            if (settings.contentType) {
                return settings.contentType.toString().trim();
            } else {
                return 'application/x-www-form-urlencoded';
            }
        })(),
        data: (function() {
            if (settings.data) {
                return object2Parameter(settings.data);
            } else {
                return "";
            }
        })(),
        url: settings.url.toString().trim(),
        success: settings.success || function() {},
        error: settings.error || function(status) {
            console.error(status);
        }
    }
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == "200" || 　xhr.status == "304") {
                var result = xhr.responseText;
                result = result.toString().trim();
                if (result && result != null && result != "") {
                    var result_ = JSON.parse(result);
                    setting.success(result_);
                } else {
                    setting.success(result);
                }
            } else {
                setting.error(xhr.status);
            }
        }
    };

    if (/get/i.test(setting.type)) {
        setting.url = setting.url + "?" + setting.data;
        xhr.open("GET", setting.url, true);
        xhr.setRequestHeader("Content-type", setting.contentType.toString().trim());
        xhr.send();
    } else if (/post/i.test(setting.type)) {
        xhr.open("POST", setting.url, true);
        xhr.setRequestHeader("Content-type", setting.contentType.toString().trim());
        xhr.send(setting.data);
    } else {
        setting.url = setting.url + "?" + setting.data;
        xhr.open(setting.type, setting.url, true);
        xhr.setRequestHeader("Content-type", setting.contentType.toString().trim());
        xhr.send();
    }
}

function checkNull(value) {
    if (!value || value == "") {
        return true;
    } else {
        return false;
    }
}

function showWarning(inputElementId, warningStr) {

    var inputElement = document.getElementById(inputElementId);
    var errorElement = document.getElementById(inputElementId + "-err");
    if (!errorElement) {
        errorElement = document.createElement("span");
        errorElement.id = inputElementId + "-err";
        errorElement.innerHTML = "<br/>" + warningStr;
        errorElement.style.color = "red";
        inputElement.style.border = "1px solid red";
        inputElement.parentNode.insertBefore(errorElement, inputElement.nextSibling);
        setTimeout(function() {
            inputElement.style.border = "";
            errorElement.parentNode.removeChild(errorElement);
        }, 3000)
    }
}

function login() {
    var userName = document.getElementById("userName");
    var password = document.getElementById("password");
    if (!checkNull(userName.value) && !checkNull(password.value)) {
        var user = {
            userName: userName.value,
            password: password.value
        };
        sendRequest({
            type: "Post",
            url: "/OrderSystem_Client/user/login",
            data: user,
            success: function(data) {
                if (data) {
                    appendUserDiv(data);
                    loadCartList();
                    hideElement("userPanel");
                    document.getElementById("menu").style.width = "63%";
                    showElement("payBtn");
                    userName.value = "";
                    password.value = "";
                }else{
                    showWarning("userName", "Username or password incorrect!");
                }
            }
        });
    } else {
        if (checkNull(userName.value)) {
            showWarning("userName", "User name cannot be empty!");
        }
        if (checkNull(password.value)) {
            showWarning("password", "password cannot be empty!")
        }
    }
}

function appendUserDiv(data) {
    var userDiv = document.getElementById("userDiv");
    var userInfo = document.getElementById("userInfo");
    if (userInfo) {
        document.getElementById("userNameSpan").innerHTML = data.uname;
    } else {
        userInfo = document.createElement("div");
        userInfo.id = "userInfo";
        var element = document.createElement("span");
        element.id = "userNameSpan";
        element.className = "user-bar-name";
        element.innerHTML = data.uname + "&nbsp;";
        var btn2 = document.createElement("button");
        btn2.innerHTML = "Orders";
        btn2.className = "orders-btn-margin";
        btn2.onclick = listOrders;
        var btn = document.createElement("button");
        btn.innerHTML = "Logout";
        btn.onclick = logout;
        userInfo.appendChild(element);
        userInfo.appendChild(btn2);
        userInfo.appendChild(btn);
        userDiv.appendChild(userInfo);
    }
}

function removeElement(elementId) {
    var element = document.getElementById(elementId);
    if (element) {
        element.parentNode.removeChild(element);
    }
}

function logout() {

    sendRequest({
        url: "/OrderSystem_Client/user/logout",
        success: function(data) {
            if (data) {
                removeElement("userInfo");
                removeElement("cartBody");
                showElement("userPanel");
                document.getElementById("menu").style.width = "45%";
                hideElement("payBtn");
                document.getElementById("menu").innerHTML = "";
                loadDishList();
                document.getElementById("cartTotal").innerHTML = 0;
            }
        }
    });
}

function register() {

    var userName = document.getElementById("regUserName");
    var tel = document.getElementById("regUserTel");
    var password = document.getElementById("regUserPassword");
    var conPassword = document.getElementById("regConUserPassword");

    if (!checkNull(userName.value) && !checkNull(tel.value) && !checkNull(password.value) && !checkNull(conPassword.value) && password.value == conPassword.value) {
        var user = {
            userName: userName.value,
            tel: tel.value,
            password: password.value,
            conPassword: conPassword.value
        }

        sendRequest({
            type: 'post',
            url: '/OrderSystem_Client/user/register',
            data: user,
            success: function(data) {
                appendUserDiv(data);
                // hideElement("userRegister");
                // hideElement("userLogin");
                hideElement("userPanel");
                document.getElementById("menu").style.width = "63%";
                showElement("payBtn");
                userName.value = "";
                tel.value = "";
                password.value = "";
                conPassword.value = "";
            }
        })
    } else {
        if (checkNull(userName.value)) {
            showWarning("regUserName", "User name cannot be empty!");
        }
        if (checkNull(tel.value)) {
            showWarning("regUserTel", "User phone number can not be empty!");
        }
        if (checkNull(password.value)) {
            showWarning("regUserPassword", "Password can not be empty!");
        }
        if (checkNull(conPassword.value)) {
            showWarning("regConUserPassword", "Confirm password can not be empty!");
        }
        if (!checkNull(password.value) && !checkNull(conPassword.value) && password.value != conPassword.value) {
            showWarning("regConUserPassword", "Passwords are not consistent!");
        }
    }
}

function loadDishList() {
    sendRequest({
        url: '/OrderSystem_Client/dish/listDish',
        success: function(dishList) {
            menuInit(dishList);
        }
    })
}

function menuInit(menu) {
    var panel = document.getElementById("menu");
    removeElement("menu-div");
    var menu_div = document.createElement("div");
    menu_div.id = "menu-div";
    menu.forEach(function(item) {
        var div = document.createElement("div");
        var img = document.createElement("img");
        img.src = "./../images/" + item.img;
        img.style.width = "230px";
        img.style.height = "160px";
        var name = document.createElement("span");
        name.innerHTML = "<br/>" + item.dname + "<br/>";
        var price = document.createElement("span");
        price.innerHTML = "$" + item.price.toFixed(2) + "<br/>";
        var btn = document.createElement("button");
        btn.onclick = function() {
            addCartElement(item);
        };
        btn.innerHTML = "Book";
        div.appendChild(img);
        div.appendChild(name);
        div.appendChild(price);
        div.appendChild(btn);
        div.style.textAlign = "center";
        div.style.float = "left";
        div.style.padding = "10px 10px 10px 10px";
        menu_div.appendChild(div)
    });
    panel.appendChild(menu_div);
}

function loadCartList() {
    sendRequest({
        url: "/OrderSystem_Client/cart/cartList",
        success: function(data) {
            if (data) {
                if (data == "Missing user") {
                    console.log(data);

                } else {
                    appendCart(data);
                }
            } else {
                removeElement("cartBody");
            }
        }
    });
    sendRequest({
        url: "/OrderSystem_Client/cart/getTotal",
        success: function(data) {
            if (data) {
                if (data == "Missing user") {
                    console.log(data);

                } else {
                    document.getElementById("cartTotal").innerHTML = data.toFixed(2);
                }
            } else {
                document.getElementById("cartTotal").innerHTML = 0;
            }
        }
    })
}

function appendCart(data) {
    var cartElement = document.getElementById("cartBody");
    var cartTable = document.getElementById("cartTable");
    if (cartElement) {
        removeElement("cartBody");
    }
    cartElement = document.createElement("tbody");
    cartElement.id = "cartBody";
    data.forEach(function(item) {
        var tr = document.createElement("tr");
        var str = "<td><img style='width: 100px;height: 65px;' src='./../images/" + item.img + "'></img></td>" +
            "<td>" + item.dname + "</td>" +
            "<td>" + item.price.toFixed(2) + "</td>" +
            "<td><button style='margin-right: 5px;' onclick=\"dishQuantityChange('" + item.did + "','reduce')\">-</button>" 
            + "<input onkeyup='this.value=this.value.replace(/\\D/g,\"\")'  onafterpaste='this.value=this.value.replace(/\\D/g,\"\")' maxlength=\"5\" style='width: 35px;text-align: center;' type='tel' value=" + item.quantity + " onchange=\"dishQuantityChange('" + item.did + "','change', this.value)\">" 
            + "<button style='margin-left: 5px;' onclick=\"dishQuantityChange('" + item.did + "','add')\">+</button></td>" 
            + "<td><button onclick=\"removeFromCart('" + item.did + "')\">remove</button></td>";
        tr.innerHTML = str;
        cartElement.appendChild(tr);
    });
    cartTable.appendChild(cartElement);
}

function removeFromCart(dishId) {

    var param = {
        did: dishId
    }

    sendRequest({
        url: "/OrderSystem_Client/cart/removeDish",
        data: param,
        success: function(data) {
            if (data) {
                if (data == "Missing user") {
                    console.log(data);

                } else {
                    loadCartList();
                }
            }
        }
    })

}

function dishQuantityChange(dishId, type, quantity) {
    var param = {
        did: dishId,
        type: type
    }
    if (type == 'change') {
        param.quantity = quantity;
    }
    sendRequest({
        url: "/OrderSystem_Client/cart/updateQuantity",
        data: param,
        success: function(data) {
            if (data) {
                if (data == "Missing user") {
                    console.log(data);

                } else {
                    loadCartList();
                }
            }
        }
    })
}

function addCartElement(dish) {
    var param = {
        did: dish.did,
        quantity: 1
    }
    sendRequest({
        url: "/OrderSystem_Client/cart/addCart",
        data: param,
        success: function(data) {
            if (data) {
                if (data == "Missing user") {
                    console.log(data);
                } else {
                    loadCartList();
                }
            }
        }
    })
}

function checkUserSession() {
    sendRequest({
        url: "/OrderSystem_Client/user/checkUser",
        success: function(user) {
            if (user) {
                appendUserDiv(user);
                loadCartList();
                // hideElement("userRegister");
                // hideElement("userLogin");
                hideElement("userPanel");
                document.getElementById("menu").style.width = "63%";
                showElement("payBtn");
            } else {
                hideElement("payBtn");
            }
        }
    })
}

function checkout() {
    sendRequest({
        url: "/OrderSystem_Client/cart/checkout",
        success: function(data) {
            // body...
            if (data == "Missing user") {
                console.log(data);
            } else {
                loadCartList();
            }
        }
    })
}

function listOrders() {
    sendRequest({
        url: "/OrderSystem_Client/order/listOrder",
        success: function(data) {
            // body...
            if (data == "Missing user") {
                console.log(data);

            } else {
                // loadCartList();
                appendOrderList(data);
            }
        }
    })
}

function appendOrderList(data) {
    if (data) {
        var html = "";
        data.forEach(function(item) {
            var str = "<div id='order-" + item.oid + "' style=\"text-align: left; width: 97%; margin: 5px 0 5px 0;border: 1px solid #000; height: auto; float: left; padding: 10px 10px 10px 10px;\">" +
                "<div style=\"float:left;width: 40%;\"><span>Order Number:</span><br/><span>" + item.oid + "</span></div>" +
                "<div style=\"float:left;width: 30%\"><span>Order Time:</span><br/><span>" + item.createDate + "</span></div>" +
                "<div style=\"float:left;width: 20%\"><span>Order Total:</span><br/><span>$" + item.total + "</span></div>" +
                "<div style=\"float:left;width: 10%\"><button onclick=\"listOrderDish('" + item.oid + "')\">Detail</button></div>" +
                "</div>";
            html += str;
        });
        var backBtn = document.createElement("button");
        backBtn.innerHTML = "Back";
        backBtn.onclick = backToDishList;
        document.getElementById("menu").innerHTML = html;
        document.getElementById("menu").appendChild(backBtn);
    }
}

function backToDishList(){
    document.getElementById("menu").innerHTML = "";
    loadDishList();
}

function listOrderDish(oid) {
    var orderlist_ = document.getElementById("order-dish-list-"+oid);
    if(orderlist_){
        var display = orderlist_.style.display;
        if(!display){
            orderlist_.style.display = "none";
        }else if(display == "none"){
            orderlist_.style.display = "block";
        }else{
            orderlist_.style.display = "none";
        }
    }else{
        sendRequest({
        url: "/OrderSystem_Client/order/listDish",
        data: { oid: oid },
        success: function(data) {
            if (data == "Missing user") {
                console.log(data);
            } else {
                appendOrderDish(data, oid);
            }
        }
    })
    }
}

function appendOrderDish(data, oid) {
    if (data) {
        var ordiv = document.getElementById("order-" + oid);
        var order_lish = document.getElementById("order-dish-list-" + oid);
        if(order_lish){
            removeElement("order-dish-list-" + oid)
        }
        order_lish = document.createElement("div");
        order_lish.id = "order-dish-list-" + oid;
        data.forEach(function(item) {
            var orderDishDiv = document.createElement("div");
            orderDishDiv.style.float = "left";
            orderDishDiv.style.width = "100%";
            var html = "<hr/>" +
                "<div style=\"float:left;width: 25%;\"><img style=\"width: 100px\" src=\"./../images/" + item.img + "\"></div>" +
                "<div style=\"float:left;width: 25%;\">" + item.dname + "</div>" +
                "<div style=\"float:left;width: 25%;\">" + item.price.toFixed(2) + "</div>" +
                "<div style=\"float:left;width: 25%;\">" + item.quantity + "</div>";
            orderDishDiv.innerHTML = html;
            order_lish.appendChild(orderDishDiv);
        });
        ordiv.appendChild(order_lish);
    }
}

function hideElement(elementId) {
    document.getElementById(elementId).style.display = "none";
}

function showElement(elementId) {
    document.getElementById(elementId).style.display = "block";
}

function init() {
    loadDishList();
    checkUserSession();
}

init();
